<template>
  <el-dialog
    append-to-body
    :close-on-click-modal="false"
    :before-close="close"
    :visible="dialogFormVisible"
    :title="title"
    width="400px"
  >
    <el-form ref="form" :model="form" :rules="rules" size="small" label-width="80px">
      <el-form-item label="角色" prop="role.id">
        <el-select v-model="form.role.id" placeholder="请选择角色">
          <el-option
            v-for="item in roles"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button type="text" @click="close">取消</el-button>
      <el-button :loading="loading" type="primary" @click="save('form')">确认</el-button>
    </div>
  </el-dialog>
</template>

<script>
import { getAll as queryAllRoles } from '@/api/system/role'
import { add } from '@/api/system/roleService'
export default {
  name: 'ServiceRole',
  data() {
    return {
      dialogFormVisible: false,
      title: '选择角色',
      loading: false,
      roles: [],
      form: {
        role: {},
        serviceId: null
      },
      rules: {
        role: {
          id: [{ required: true, message: '请选择角色', trigger: 'changer' }]
        }
      }
    }
  },
  methods: {
    close() {
      this.$refs['form'].resetFields()
      this.dialogFormVisible = false
      this.$emit('fetch-data-role')
    },
    openEntity(data) {
      if (data.id !== null && data.id !== undefined) {
        this.form.serviceId = data.id
        this.dialogFormVisible = true
        this.initRoles()
      } else {
        this.$message.error('未获取服务信息')
      }
    },
    initRoles() {
      queryAllRoles().then(res => {
        this.roles = res
      }).catch(() => {
        console.log('获取角色信息失败')
      })
    },
    save(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          add(this.form).then(res => {
            this.close()
          }).catch(() => {
            console.log('保存角色信息失败！')
          })
        } else {
          console.log('error submit!!')
          return false
        }
      })
    }
  }
}
</script>

<style scoped>

</style>
